import EventManager from "./EventManager";
import GameData from "./GameData";

export default class Game extends Laya.Script {

    /** @prop {name:btnback, type:Node} */
    public btnback: Laya.Button;

    // main容器
    /** @prop {name:spMain, type:Node} */
    public spMain: Laya.Sprite;

    // 登录
    /** @prop {name:btnLogin, type:Node} */
    public btnLogin: Laya.Button;

    // 保存玩家角色信息
    /** @prop {name:btnRole, type:Node} */
    public btnRole: Laya.Button;

    // 支付
    /** @prop {name:btnPay, type:Node} */
    public btnPay: Laya.Button;

    // pay容器
    /** @prop {name:spPay, type:Node} */
    public spPay: Laya.Sprite;

    // Mean容器
    /** @prop {name:spMean, type:Node} */
    public spMean: Laya.Sprite;

    // 查询初始化
    /** @prop {name:btnQueryInit, type:Node} */
    public btnQueryInit: Laya.Button;

    // 查询是否支持支付
    /** @prop {name:btnQueryPay, type:Node} */
    public btnQueryPay: Laya.Button;

    // 查询商品信息
    /** @prop {name:btnQueryProducts, type:Node} */
    public btnQueryProducts: Laya.Button;

    // 发起购买
    /** @prop {name:btnPurchase, type:Node} */
    public btnPurchase: Laya.Button;

    // 查询购买记录
    /** @prop {name:btnOwnedPurchases, type:Node} */
    public btnOwnedPurchases: Laya.Button;

    // 补单
    /** @prop {name:btnMakeup, type:Node} */
    public btnMakeup: Laya.Button;


    // queryProducts容器
    /** @prop {name:spQueryProducts, type:Node} */
    public spQueryProducts: Laya.Sprite;

    // 查询消耗型商品信息
    /** @prop {name:btnQueryConsumeProducts, type:Node} */
    public btnQueryConsumeProducts: Laya.Button;

    // 查询非消耗型商品信息
    /** @prop {name:btnQueryNonConsumeProducts, type:Node} */
    public btnQueryNonConsumeProducts: Laya.Button;

    // 查询订阅商品信息
    /** @prop {name:btnQuerySubscriptionProducts, type:Node} */
    public btnQuerySubscriptionProducts: Laya.Button;


    // purchase容器
    /** @prop {name:spPurchase, type:Node} */
    public spPurchase: Laya.Sprite;

    // 购买消耗商品测试
    /** @prop {name:btnPurchaseConsumeProducts, type:Node} */
    public btnPurchaseConsumeProducts: Laya.Button;

    // 购买非消耗商品测试
    /** @prop {name:btnPurchaseNonConsumeProducts, type:Node} */
    public btnPurchaseNonConsumeProducts: Laya.Button;

    // 购买订阅行商品测试
    /** @prop {name:btnPurchaseSubscriptionProducts, type:Node} */
    public btnPurchaseSubscriptionProducts: Laya.Button;


    // makeup容器
    /** @prop {name:spMakeup, type:Node} */
    public spMakeup: Laya.Sprite;

    // 补单消耗型商品
    /** @prop {name:btnMakeupConsumeProducts, type:Node} */
    public btnMakeupConsumeProducts: Laya.Button;

    // 补单非消耗型商品
    /** @prop {name:btnMakeupNonConsumeProducts, type:Node} */
    public btnMakeupNonConsumeProducts: Laya.Button;

    // 补单订阅型商品
    /** @prop {name:btnMakeupSubscriptionProducts, type:Node} */
    public btnMakeupSubscriptionProducts: Laya.Button;


    // queryPurchase容器
    /** @prop {name:spQueryPurchase, type:Node} */
    public spQueryPurchase: Laya.Sprite;

    // 查询消耗型购买记录
    /** @prop {name:btnQueryPurchaseProducts, type:Node} */
    public btnQueryPurchaseProducts: Laya.Button;

    // 查询非消耗型购买记录
    /** @prop {name:btnQueryNonPurchaseProducts, type:Node} */
    public btnQueryNonPurchaseProducts: Laya.Button;

    // 查询订阅型购买记录
    /** @prop {name:btnQuerySubscriptionPurchaseProducts, type:Node} */
    public btnQuerySubscriptionPurchaseProducts: Laya.Button;


    // 内容显示
    /** @prop {name:txtContent, type:Node} */
    public txtContent: Laya.Text;

    // 标题
    /** @prop {name:txtTitle, type:Node} */
    public txtTitle: Laya.Label;

    // 设置
    /** @prop {name:btnSet, type:Node} */
    public btnSet: Laya.Button;


    constructor() { super(); }

    onEnable(): void {
        this.spMain.visible = true;
        this.spPay.visible = false;
        this.txtTitle.text = "主页";

        this.btnback.on(Laya.Event.CLICK, this, this.onClickBack);
        this.txtContent.text = "";
        this.btnLogin.on(Laya.Event.CLICK, this, this.onClickLogin);
        this.btnRole.on(Laya.Event.CLICK, this, this.onClickRole);
        this.btnPay.on(Laya.Event.CLICK, this, this.onClickPay);

        // Mean
        this.btnQueryInit.on(Laya.Event.CLICK, this, this.onClickIAPKitInit);
        this.btnQueryPay.on(Laya.Event.CLICK, this, this.onClickQueryPayStatus);
        this.btnQueryProducts.on(Laya.Event.CLICK, this, this.onClickQueryProducts);
        this.btnPurchase.on(Laya.Event.CLICK, this, this.onClickPurchase);
        this.btnOwnedPurchases.on(Laya.Event.CLICK, this, this.onClickOwnedPurchases);
        this.btnMakeup.on(Laya.Event.CLICK, this, this.onClickMakeup);

        // queryProducts
        this.btnQueryConsumeProducts.on(Laya.Event.CLICK, this, this.onClickQueryConsumeProducts);
        this.btnQueryNonConsumeProducts.on(Laya.Event.CLICK, this, this.onClickQueryNonConsumeProducts);
        this.btnQuerySubscriptionProducts.on(Laya.Event.CLICK, this, this.onClickQuerySubscriptionProducts);

        // purchase
        this.btnPurchaseConsumeProducts.on(Laya.Event.CLICK, this, this.onClickPurchaseConsumeProducts);
        this.btnPurchaseNonConsumeProducts.on(Laya.Event.CLICK, this, this.onClickPurchaseNonConsumeProducts);
        this.btnPurchaseSubscriptionProducts.on(Laya.Event.CLICK, this, this.onClickPurchaseSubscriptionProducts);

        // makeup
        this.btnMakeupConsumeProducts.on(Laya.Event.CLICK, this, this.onClickMakeupConsumeProducts);
        this.btnMakeupNonConsumeProducts.on(Laya.Event.CLICK, this, this.onClickMakeupNonConsumeProducts);
        this.btnMakeupSubscriptionProducts.on(Laya.Event.CLICK, this, this.onClickMakeupSubscriptionProducts);

        // queryPurchase
        this.btnQueryPurchaseProducts.on(Laya.Event.CLICK, this, this.onClickQueryPurchaseProducts);
        this.btnQueryNonPurchaseProducts.on(Laya.Event.CLICK, this, this.onClickQueryNonPurchaseProducts);
        this.btnQuerySubscriptionPurchaseProducts.on(Laya.Event.CLICK, this, this.onClickQuerySubscriptionPurchaseProducts);

        this.btnSet.on(Laya.Event.CLICK, this, this.onClickSet);

        EventManager.on(EventManager.CONTENT_INFO_CHANGE, this, this.onChangeTxtContent);
    }

    onDisable(): void {
    }

    onClickSet() {
        Laya.Scene.open("SetDialog.scene", false);
    }

    /** 返回主页 */
    onClickBack() {
        if (this.spMean.visible) {
            this.txtTitle.text = "主页";
            this.spMain.visible = true;
            this.spPay.visible = false;
        } else {
            if (!this.spMain.visible) {
                this.txtTitle.text = "支付";
                this.spQueryProducts.visible = this.spPurchase.visible = this.spMakeup.visible = this.spQueryPurchase.visible = false;
                this.spMean.visible = true;
            }
        }

    }

    /**
     * Click:登录
     */
    async onClickLogin() {
        // 第1步:
        this.onChangeTxtContent("\n======>发起初始化init():");
        let res: string = await this.onAddCallbackPromise("init", "");
        this.onChangeTxtContent(">:init " + res);
        let resObj: ResponseParam = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 初始化失败
            return;
        }


        // 第2步:
        this.onChangeTxtContent("\n======>发起联合登录unionlogin():");
        res = await this.onAddCallbackPromise("unionlogin", "");
        this.onChangeTxtContent(">:unionlogin " + res);
        resObj = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 联合登陆失败-可以做些业务逻辑
            return;
        }
        // 处理登录数据
        GameData.onParseData(resObj.data);


        // 第3步:
        this.onChangeTxtContent("\n======>发起华为账号登录hwLogin():");
        res = await this.onAddCallbackPromise("hwLogin", JSON.stringify(GameData.gamePlayerData));
        this.onChangeTxtContent(">:hwLogin " + res);
        resObj = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 华为账号登录-可以做些业务逻辑
            return;
        }
        if (resObj.extraData == "NeedBinding") {
            // 需要进行绑定
            this.onChangeTxtContent("\n======>发起绑定bindPlayer():");
            const param = {
                "thirdOpenId": "111111", // 游戏官方账号
                "teamPlayerId": GameData.gamePlayerData.localPlayer.teamPlayerId
            }
            res = await this.onAddCallbackPromise("bindPlayer", JSON.stringify(param));
            this.onChangeTxtContent(">:bindPlayer " + res);
            resObj = JSON.parse(res);
            if (resObj.state == "Failed") {
                // 绑定失败-可以做些业务逻辑
                return;
            }
        }


        // 第4步:
        this.onChangeTxtContent("\n======>发起合规校验verifyLocalPlayer():");
        res = await this.onAddCallbackPromise("verifyLocalPlayer", GameData.gamePlayerData.boundPlayerInfo.thirdOpenId);
        this.onChangeTxtContent(">:verifyLocalPlayer " + res);
        resObj = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 合规校验-可以做些业务逻辑
            return;
        }
    }

    /**
     * Click:保存玩家角色信息
     */
    async onClickRole() {
        // savePlayerRole
        this.onChangeTxtContent("\n======>发起玩家服务-保存玩家角色信息:");
        let param: GSKPlayerRole = {
            roleId: '123',
            roleName: 'Jason',
            serverId: '456',
            serverName: 'Zhangshan',
            gamePlayerId: GameData.gamePlayerData.localPlayer.gamePlayerId,
            teamPlayerId: '000'
        };
        let res = await this.onAddCallbackPromise("submitPlayerRole", JSON.stringify(param));
        this.onChangeTxtContent(">:submitPlayerRole " + res);
    }

    /**
     * Click:支付
     */
    onClickPay() {
        this.txtTitle.text = "支付";
        this.spMain.visible = false;
        this.spPay.visible = this.spMean.visible = true;
        this.spQueryProducts.visible = this.spPurchase.visible = this.spMakeup.visible = this.spQueryPurchase.visible = false;
    }

    /**
     * Click:IAPKit初始化
     */
    async onClickIAPKitInit() {
        this.onChangeTxtContent("\n======>IAPKit初始化:");
        let res = await this.onAddCallbackPromise("initIAPKit", "");
        this.onChangeTxtContent(">:initIAPKit " + res);
    }

    /**
     * Click:查询是否支持支付
     */
    async onClickQueryPayStatus() {
        this.onChangeTxtContent("\n======>查询是否支持支付:");
        let res = await this.onAddCallbackPromise("queryEnv", "");
        this.onChangeTxtContent(">:queryEnv " + res);
        let resObj: ResponseParam = JSON.parse(res);
        if (resObj.state == "Failed") {
            // 不支持支付
            return;
        }
        GameData.isSupportIAPKit = true;
    }

    /**
     * Click:查询商品信息
     */
    onClickQueryProducts() {
        this.txtTitle.text = "查询商品信息";
        this.spMean.visible = false;
        this.spQueryProducts.visible = true;
    }

    /**
     * Click:发起购买
     */
    onClickPurchase() {
        this.txtTitle.text = "发起购买";
        this.spMean.visible = false;
        this.spPurchase.visible = true;

    }

    /**
     * Click:查询购买记录
     */
    onClickOwnedPurchases() {
        this.txtTitle.text = "查询购买记录";
        this.spMean.visible = false;
        this.spQueryPurchase.visible = true;
    }

    /**
     * Click:补单
     */
    onClickMakeup() {
        this.txtTitle.text = "补单";
        this.spMean.visible = false;
        this.spMakeup.visible = true;
    }



    /**
     * Click:查询消耗型商品信息
     */
    onClickQueryConsumeProducts() {
        this.onQueryProductsInfo(0);
    }

    /**
     * Click:查询非消耗型商品信息
     */
    onClickQueryNonConsumeProducts() {
        this.onQueryProductsInfo(1);
    }

    /**
     * Click:查询订阅商品信息
     */
    onClickQuerySubscriptionProducts() {
        this.onQueryProductsInfo(2);
    }

    /** 查询商品信息 */
    async onQueryProductsInfo(type: number) {
        if (!GameData.isSupportIAPKit) {
            this.onChangeTxtContent(">:Tips 先查询是否支持支付或暂不支持登录支付。");
            return;
        }

        // 0.查询消耗型商品信息   1.查询非消耗型商品信息  2.查询订阅商品信息
        let productIds = [];
        switch (type) {
            case 0:
                productIds = ["consumeProduct001"];
                this.onChangeTxtContent("\n======>查询消耗型商品信息:");
                break;
            case 1:
                productIds = ["noConsumeProduct001"];
                this.onChangeTxtContent("\n======>查询非消耗型商品信息:");
                break;
            case 2:
                productIds = ["subscribeProduct001"];
                this.onChangeTxtContent("\n======>查询订阅型商品信息:");
                break;
        }
        const param = {
            // 查询的商品必须是您在AppGallery Connect网站配置的商品
            productIds: productIds,
            // productType:
            // iap.ProductType.CONSUMABLE：消耗型商品;0
            // iap.ProductType.NONCONSUMABLE：非消耗型商品;1
            productType: type
        }
        let res = await this.onAddCallbackPromise("queryProducts", JSON.stringify(param));
        this.onChangeTxtContent(">:queryProducts " + res);
    }


    /**
     * Click:购买消耗商品测试
     */
    onClickPurchaseConsumeProducts() {
        // purchase(0)
        this.onPurchaseProductsTest(0);
    }

    /**
     * Click:购买非消耗商品测试
     */
    onClickPurchaseNonConsumeProducts() {
        // purchase(1)
        this.onPurchaseProductsTest(1);
    }

    /**
     * Click:购买订阅行商品测试
     */
    onClickPurchaseSubscriptionProducts() {
        // purchase(2)
        this.onPurchaseProductsTest(2);
    }

    /** 购买商品 */
    async onPurchaseProductsTest(type: number) {
        if (!GameData.isSupportIAPKit) {
            this.onChangeTxtContent(">:Tips 先查询是否支持支付或暂不支持登录支付。");
            return;
        }

        // 0.购买消耗商品  1.购买非消耗商品  2.购买订阅行商品
        let res: string = "";
        let productId: string = "";
        switch (type) {
            case 0:
                productId = "consumeProduct001";
                this.onChangeTxtContent("\n======>购买消耗商品:");
                break;
            case 1:
                productId = "noConsumeProduct001";
                this.onChangeTxtContent("\n======>购买非消耗商品:");
                break;
            case 2:
                productId = "subscribeProduct001";
                this.onChangeTxtContent("\n======>购买订阅行商品:");
                break;
        }
        const param = {
            // 通过purchase接口购买的商品必须是您在AppGallery Connect网站配置的商品
            productId: productId,
            productType: type
        }
        res = await this.onAddCallbackPromise("buy", JSON.stringify(param));
        this.onChangeTxtContent(">:buy " + res);
        let resobj: ResponseParam = JSON.parse(res);
        if (resobj.state == "Success") {
            // 购买成功后，如果有服务端验签，前端到这里就结束了
            // 或把JSON.parse(resobj.data).purchaseData发给服务器进行验签
            // return;


            // 下面演示前端本地验签和完成订单
            this.onLocalSVFinishTest(type, [JSON.parse(resobj.data).purchaseData]);
        }
        else if (resobj.extraData) {
            // 购买失败了-查询到可以补单的商品数据
            let resobj2: ResponseParam = JSON.parse(resobj.extraData);
            if (resobj2.state == "Success") {
                let purchaseDataList: string[] = JSON.parse(resobj2.data);
                // 有服务端验签，就把purchaseDataList数据发到服务端进行验签
                // return;


                // 下面演示前端本地验签和完成订单
                this.onLocalSVFinishTest(type, purchaseDataList);
            }
        }
    }


    /**
     * Click:补单消耗型商品
     */
    onClickMakeupConsumeProducts() {
        // makeUp(0)
        this.onMakeupProducts(0);
    }

    /**
     * Click:补单非消耗型商品
     */
    onClickMakeupNonConsumeProducts() {
        // makeUp(1)
        this.onMakeupProducts(1);
    }

    /**
     * Click:补单订阅型商品
     */
    onClickMakeupSubscriptionProducts() {
        // makeUp(2)
        this.onMakeupProducts(2);
    }

    /** 补单商品 */
    async onMakeupProducts(type: number) {
        if (!GameData.isSupportIAPKit) {
            this.onChangeTxtContent(">:Tips 先查询是否支持支付或暂不支持登录支付。");
            return;
        }
        switch (type) {
            case 0:
                this.onChangeTxtContent("\n======>补单消耗型商品:");
                break;
            case 1:
                this.onChangeTxtContent("\n======>补单非消耗型商品:");
                break;
            case 2:
                this.onChangeTxtContent("\n======>补单订阅型商品:");
                break;
        }
        // 1.先-查询-有没有需要补单的商品
        let res = await this.onAddCallbackPromise("queryPurchase", JSON.stringify([type, 1]));
        this.onChangeTxtContent(">:queryPurchase " + res);
        let resObj: ResponseParam = JSON.parse(res);
        if (resObj.state == "Success") {
            let purchaseDataList: string[] = JSON.parse(resObj.data);
            // 有需要补单的订单数据，如果有服务端验签就把数据purchaseDataList发送给服务端
            // return;


            // 下面演示前端本地验签和完成订单
            this.onLocalSVFinishTest(type, purchaseDataList);
        }
    }


    /**
     * Click:查询消耗型购买记录
     */
    onClickQueryPurchaseProducts() {
        // queryPurchases(0)
        this.onQueryPurchaseProducts(0);
    }

    /**
     * Click:查询非消耗型购买记录
     */
    onClickQueryNonPurchaseProducts() {
        // queryPurchases(1)
        this.onQueryPurchaseProducts(1);
    }

    /**
     * Click:查询订阅型购买记录
     */
    onClickQuerySubscriptionPurchaseProducts() {
        // queryPurchases(2)
        this.onQueryPurchaseProducts(2);
    }

    /** 查询购买记录 */
    async onQueryPurchaseProducts(type: number) {
        if (!GameData.isSupportIAPKit) {
            this.onChangeTxtContent(">:Tips 先查询是否支持支付或暂不支持登录支付。");
            return;
        }
        switch (type) {
            case 0:
                this.onChangeTxtContent("\n======>查询消耗型购买记录:");
                break;
            case 1:
                this.onChangeTxtContent("\n======>查询非消耗型购买记录:");
                break;
            case 2:
                this.onChangeTxtContent("\n======>查询订阅型购买记录:");
                break;
        }
        let res = await this.onAddCallbackPromise("queryPurchase", JSON.stringify([type, 0]));
        this.onChangeTxtContent(">:queryPurchase " + res);
    }




    /**
     * 这里是前端进行：验签->完成订单 (演示)
     * @param purchaseDataList 采购数据列表
     */
    async onLocalSVFinishTest(productType: number, purchaseDataList: string[]) {
        for (let i = 0; i < purchaseDataList.length; i++) {
            const res: string = await this.onAddCallbackPromise("dealPurchaseData", JSON.stringify([productType, purchaseDataList[i]]));
            this.onChangeTxtContent(">:dealPurchaseData " + purchaseDataList[i] + " | " + res);
            const resObj: ResponseParam = JSON.parse(res);
            // 本地验签成功-进行完成订单
            if (resObj.state == "Success") {
                const res2: string = await this.onAddCallbackPromise("finishPurchase", resObj.data);
                this.onChangeTxtContent(">:finishPurchase " + purchaseDataList[i] + " | " + res2);
            }
        }
    }

    /**
     * 创建一个promise返回
     * @param funName 反射的方法名
     * @param param 传参
     * @returns 
     */
    onAddCallbackPromise(funName: string, param: string): Promise<string> {
        return new Promise((resolve, reject) => {
            let bridge = Laya.Browser.window.PlatformClass.createClass("entry/src/main/ets/AccountDemo");
            bridge.callWithBack((result: string) => {
                resolve(result);
            }, funName, param);
        });
    }

    /**
     * 更改显示内容
     * @param str 内容
     */
    onChangeTxtContent(str: string) {
        this.txtContent.text = this.txtContent.text + str + "\n";
        this.txtContent.scrollY = this.txtContent.maxScrollY;
    }

}